import { useState, useEffect, useRef } from "react";
import { useImperativeHandle, forwardRef } from "react";
import "./Timer.css";

/// 组件的状态
/// seconds === null, seconds > 0
/// millisecond == null, millisecond > 0, millisecond <= 0

function Timer({ seconds, onDone }, ref) {
    // 声明组件有一个millisecond状态，初始值是null，可以使用setMillisecond函数更新该状态
    const [millisecond, setMillisecond] = useState(null);

    // 声明组件内的一个“引用”，存放setInterval生成定时器的标号
    const intervalRef = useRef(null);

    // 在组件中定义可以外部访问的方法
    useImperativeHandle(
        ref,
        () => ({
            pause: () => {
                if (intervalRef.current !== null) {
                    clearInterval(intervalRef.current);
                    intervalRef.current = null;
                } else {
                    intervalRef.current = setInterval(() => {
                        setMillisecond((millisecond) => millisecond - 100);
                    }, 100);
                }
            },
        }),
        []
    );

    useEffect(() => {
        if (seconds === null) {
            setMillisecond(null);
            return;
        }

        setMillisecond(seconds * 1000); // 根据seconds更新millisecond

        intervalRef.current = setInterval(() => {
            setMillisecond((millisecond) => millisecond - 100);
        }, 100);

        return () => {
            if (intervalRef.current !== null) {
                clearInterval(intervalRef.current);
                intervalRef.current = null;
            }
        };
    }, [seconds]);

    useEffect(() => {
        if (millisecond !== null && millisecond <= 0) {
            clearInterval(intervalRef.current);
            setMillisecond(null);

            if (onDone) {
                onDone();
            }
        }
    }, [millisecond, onDone]);

    useEffect(() => {
        return () => {
            // 如果取消挂载组件时，定时器interval还在，则取消该定时器
            if (intervalRef.current !== null) {
                clearInterval(intervalRef.current);
                intervalRef.current = null;
            }
        };
    }, []);

    return (
        <div className="timer monospace">
            <div className="integer">{`${Math.floor(millisecond / 1000)}`}</div>
            <div className="seperator">.</div>
            <div className="fraction">
                {`${Math.floor((millisecond % 1000) / 100)}`}
            </div>
        </div>
    );
}

export default forwardRef(Timer);
